package com.dhq.myapp.util

import android.content.Context
import com.tencent.mmkv.MMKV

/**
 * DESC
 * Created by admin on 2020/5/1.
 */
object DataStorageUtils {

    fun initialize(context: Context) {
        MMKV.initialize(context)
    }

    /**
     * 存储数据
     */
    fun putObject(key: String, value: Any?) {
        val mmkv = MMKV.defaultMMKV()
        when (value) {
            is String -> mmkv.encode(key, value)
            is Boolean -> mmkv.encode(key, value)
            is Int -> mmkv.encode(key, value)
            is Long -> mmkv.encode(key, value)
            is Float -> mmkv.encode(key, value)
            is Double -> mmkv.encode(key, value)
            is ByteArray -> mmkv.encode(key, value)
        }
    }

    fun getStringValue(key: String): String? {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeString(key)
    }

    fun getStringValue(key: String, defaultValue: String): String {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeString(key, defaultValue) ?: defaultValue
    }

    fun getBooleanValue(key: String, defaultValue: Boolean): Boolean {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeBool(key, defaultValue)
    }

    fun getIntValue(key: String, defaultValue: Int): Int {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeInt(key, defaultValue)
    }

    fun getLongValue(key: String, defaultValue: Long): Long {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeLong(key, defaultValue)
    }

    fun getFloatValue(key: String, defaultValue: Float): Float {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeFloat(key, defaultValue)
    }

    fun getDoubleValue(key: String, defaultValue: Double): Double {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeDouble(key, defaultValue)
    }

    fun getBytesValue(key: String): ByteArray? {
        val mmkv = MMKV.defaultMMKV()
        return mmkv.decodeBytes(key)
    }

    /**
     * 移除数据
     */
    fun removeValue(key: String) {
        val mmkv = MMKV.defaultMMKV()
        mmkv.remove(key)
    }

    /**
     * 移除多个数据
     */
    fun removeValues(vararg keys: String) {
        val mmkv = MMKV.defaultMMKV()
        keys.forEach { key ->
            mmkv.remove(key)
        }
    }

    /**
     * 清空数据
     */
    fun clear() {
        val mmkv = MMKV.defaultMMKV()
        mmkv.clearAll()
    }
}
